/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.webanovare.ruzzle.misc;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 *
 * @author ekbga
 */
final public class Trie {

    final private class TrieNode {

        boolean isWord = false;
        Character label;
        Map<Character, TrieNode> children = new HashMap<Character, TrieNode>();

        public TrieNode(Character c) {
            this.label = c;
        }
    }
    final private TrieNode root;

    public Trie() {
        this.root = new TrieNode('@');
    }

    public Trie(File wordList) throws FileNotFoundException {
        this.root = new TrieNode('@');
        Scanner sc = null;
        try {
            sc = new Scanner(wordList);

            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                this.addWord(line);
            }
        } finally {
            if (sc != null) {
                sc.close();
            }
        }
    }

    public void addWord(String word) {
        TrieNode current = this.root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (!current.children.containsKey(c)) {
                current.children.put(c, new TrieNode(c));
            }
            current = current.children.get(c);

            if (i == word.length() - 1) {
                current.isWord = true;
            }
        }
    }

    public boolean checkWord(String word) {
        TrieNode current = this.root;

        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);

            if (current.children.containsKey(c)) {
                current = current.children.get(c);

                if (i == word.length() - 1 && current.isWord) {
                    return true;
                }
            } else {
                return false;
            }
        }
        return false;
    }

    public boolean hasExtension(String word) {
        TrieNode node = root;
        for (Character c : word.toCharArray()) {
            if (node.children.get(c) == null) {
                return false;
            }
            node = node.children.get(c);
        }
        return true;
    }
}